package org.example.meetingsystem.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.meetingsystem.DTO.LoginDTO;
import org.example.meetingsystem.DTO.RegisterDTO;
import org.example.meetingsystem.entity.User;
import org.example.meetingsystem.enums.UserStatus;
import org.example.meetingsystem.annotation.RequireAuth;
import org.example.meetingsystem.service.UserService;
import org.example.meetingsystem.util.JwtUtil;
import org.example.meetingsystem.util.ResponseUtil;
import org.example.meetingsystem.util.Result;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "用户认证与注册", description = "登录、注册、获取当前用户信息")
public class AuthController {

    private final UserService userService;
    private final JwtUtil jwtUtil;
    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "输入用户名与密码，返回 JWT Token 和用户信息")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginDTO loginDTO) {
        User user = userService.findByUsername(loginDTO.getUsername());

        if (user == null || !passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            return ResponseUtil.error("用户名或密码错误");
        }

        if (user.getStatus() != UserStatus.ACTIVE) {
            return ResponseUtil.error("账号未激活或已被冻结");
        }

        String token = jwtUtil.generateToken(user);
        Map<String, Object> result = userService.login(loginDTO);
        result.put("token", token); // 确保 token 写入

        return ResponseUtil.success("登录成功", result);
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "提交用户注册信息，创建新账号，默认状态为待审核")
    public Result<String> register(@Valid @RequestBody RegisterDTO registerDTO) {
        User existUser = userService.findByUsername(registerDTO.getUsername());
        if (existUser != null) {
            return ResponseUtil.error("用户名已存在");
        }

        userService.register(registerDTO);
        return ResponseUtil.success("注册成功");
    }

    @GetMapping("/current")
    @RequireAuth
    @Operation(summary = "获取当前登录用户", description = "从请求中获取当前登录的用户信息")
    public Result<User> getCurrentUser(
            @Parameter(hidden = true) HttpServletRequest request) {
        User currentUser = (User) request.getAttribute("currentUser");
        return ResponseUtil.success(currentUser);
    }
}
